package com.imonsoft.common.util;

/**
 * 
 */

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * 
 * @author LiQianHui
 * @date 2012-10-11
 * @version 2012
 */
public abstract class JsonUtil {

	private final static Log logger = LogFactory.getLog(JsonUtil.class);
	private static Gson gsonForBean = new GsonBuilder().create();

	/**
	 * 
	 * 将bean转换成json串，bean中可以包含自定义属性，<br>
	 * 转换后的json串是有层次结构的<br>
	 * Date类型的将被按字符串赋给json串<br>
	 * 
	 * <link>http://sites.google.com/site/gson/Home</link>
	 * 
	 * @param bean
	 * @return json串
	 */
	public static String bean2json(Object bean) {
		String jsonStr = gsonForBean.toJson(bean);
		logger.info("转换后的JSON：" + jsonStr);
		return jsonStr;
	}

	/**
	 * 将具有JSON字符串的转换成指定的bean
	 *  简单Bean
	 * @param json
	 * @param classType 简单bean
	 * @return
	 */
	public static <T> T json2Bean(String json,Class<T> classType) {
		logger.info("转换前的JSON串："+json);
		return gsonForBean.fromJson(json, classType);
	}
	
	/**
	 * json转为带泛型的解析方式
	 * @param json [{id:'1',ids:'zs',name:'s'},{id:'2',ids:'3',name:'dd'}]
	 * @param type new TypeToken<List<Store>>(){}
	 * @return
	 */
	public static <T> T json2Bean(String json,TypeToken<T> type) {
		logger.info("转换前的JSON串："+json);
		return gsonForBean.fromJson(json, type.getType());
	}
	public static void main(String[] args) {
		
		//MAP json
		String mapJson ="{'name':'ee','productCode':'reg','tsProvider.id':'1','spec':'','minInventory':'','maxInventory':'','guaranteePeriod':'','purchasePrice':'','state':'1','remark':'','accountsPrice':'','storePrice':''}";
		Map<String,String> productAddMap=JsonUtil.json2Bean(mapJson,new TypeToken<Map<String,String>>(){});
		System.out.println(productAddMap);

	}
}
